<template>
  <div></div>
</template>

<script>
  import { imInit, imGetToken, RongIMLibInit } from '@/api/im'
  import { setImToken, setImUnreadSeller, setImUnreadBuyer } from '@/utils/auth'
  import { getMemberInfo } from '@/api/home'

  export default {
    data() {
      return {
        customerInfo: {},
        getImTokenData: ''
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
    },
    onShow() {
      this.initEls()
    },
    mounted() {
      setTimeout(() => {
        this.initEls()
      }, 100)
    },
    methods: {
      initEls() {
        if (!this.getCustomerId) return
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          this.customerInfo = response.data
          this.imGetToken()
        }).catch(() => {
        })
      },
      imGetToken() {
        imGetToken({
          userId: this.getCustomerId,
          name: this.customerInfo.nickname,
          portraitUri: this.customerInfo.avatar
        }).then((response) => {
          this.getImTokenData = response.token
          setImToken(response.token)
          this.imConnect()
        }).catch((res) => {
        })
      },
      imConnect() {
        const im = imInit()
        im.connect({ token: this.getImTokenData }).then(user => {
          console.log('all 链接成功, 链接用户 id 为: ', user.id)
          this.getImTotalUnread()
        }).catch(error => {
          if (error.code !== 34001) {
            console.log('all 链接失败: ', error.code, error.msg)
            return
          }
          console.log('all 链接失败: ', error.code, error.msg)
          this.getImTotalUnread()
        })
      },
      getImTotalUnread() {
        const im = imInit()
        im.Conversation.getTotalUnreadCount().then(function(totalUnreadCount) {
          setImUnreadBuyer(totalUnreadCount)
          console.log('all 获取未读总数成功', totalUnreadCount)
        })
        // 获取指定会话未读数
        // let conversation = im.Conversation.get({
        //     targetId: this.getCustomerId,
        //     type: RongIMLib.CONVERSATION_TYPE.PRIVATE
        // });
        // conversation.read().then(function(count) {
        //     console.log('获取指定会话未读数成功'， count);
        // })
        const RongIMLib = RongIMLibInit()
        let conversation = im.Conversation.get({
          targetId: this.getMemberId,
          type: RongIMLib.CONVERSATION_TYPE.PRIVATE
        })
        conversation.getUnreadCount().then(function(count) {
          setImUnreadSeller(count)
          console.log('all 获取指定会话未读数成功', count)
        })
      }
    }
  }
</script>
